package handler

import (
	"gin-vben-admin/pkg/jwt"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type Handler struct {
	logger *zap.Logger
}

func NewHandler(logger *zap.Logger) *Handler {
	return &Handler{
		logger: logger,
	}
}

func IsLogin(ctx *gin.Context) (auth *jwt.TokenClaims, err error) {

	if v, ok := ctx.Value("claims").(*jwt.TokenClaims); ok {
		return v, nil
	}
	return
}

// UserId 当前登陆用户id
func UserId(ctx *gin.Context) int64 {
	auth, err := IsLogin(ctx)
	if err != nil {
		return 0
	}
	return auth.UserId
}

// Username 当前登陆用户id
func Username(ctx *gin.Context) string {
	auth, err := IsLogin(ctx)
	if err != nil {
		return ""
	}
	return auth.Username
}

func GetBearerToken(ctx *gin.Context) string {
	tokenStr := ctx.Request.Header.Get("Authorization")
	if len(tokenStr) > 0 && tokenStr[0:7] == "Bearer " {
		return tokenStr[7:]
	}
	//websocket
	return ctx.Request.Header.Get("Sec-WebSocket-Protocol")
}
